package com.lcg.word.screen

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewModelScope
import coil.compose.AsyncImage
import com.lcg.base.Core
import com.lcg.base.PreferenceKTX
import com.lcg.base.net.download
import com.lcg.base.net.flow.get
import com.lcg.word.Base
import com.lcg.word.BaseViewModel
import com.lcg.word.DigitalInkManager
import com.lcg.word.bean.Book
import com.lcg.word.bean.BookDb
import com.lcg.word.bean.BookUnit
import com.lcg.word.bean.initDao
import com.lcg.word.launched
import com.lcg.word.screen.destinations.BookScreenDestination
import com.lcg.word.viewModel
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.delay
import java.io.IOException

/**
 * 首页
 *
 * @author lei.chuguang Email:475825657@qq.com
 */
@Preview(showBackground = true, widthDp = 1333, heightDp = 800)
@Composable
@RootNavGraph(start = true) // 该注解表示根路由页面
@Destination
fun HomeScreen(
    navigator: DestinationsNavigator? = null,
    vm: HomeVM = viewModel(navigator, "首页")
) {
    LaunchedEffect(Unit) {
        vm.load()
    }
    Base(vm) {
        LazyVerticalGrid(
            columns = GridCells.Adaptive(200.dp),
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp, 0.dp)
        ) {
            items(vm.books) {
                AsyncImage(model = it.pic,
                    contentDescription = it.name,
                    contentScale = ContentScale.FillWidth,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(6.dp)
                        .clickable { vm.detail(it) })
            }
        }
    }
}

class HomeVM : BaseViewModel() {
    var books by mutableStateOf(emptyList<Book>())
    private val newBookId = PreferenceKTX.getLong("bookId")

    init {
        loadingUiDelay = 0
        showBack = false
        rightText = if (newBookId > 0) "复习已学课本" else ""
    }

    suspend fun load() {
        if (books.isNotEmpty()) return
        loadingCancelable = false
        get<ArrayList<Book>>("/books.json", fail = { _, t ->
            val b = t is IOException
            if (b) launched(viewModelScope) { delay(1000); load() }
            b
        }).collect {
            books = it
        }
    }

    fun detail(book: Book) {
        loadingCancelable = true
        launched(viewModelScope) {
            var file = Core.context!!.getFileStreamPath("data.db")
            if (!file.exists()) {
                file = download("/data.db", file, progress = { p, t ->
                    if (t > 0) loadingMessage = "加载进度${p * 100 / t}%"
                }) { _, _, f ->
                    f.delete()
                }
            }
            if (file != null && initDao(file)) {
                navigator?.navigate(BookScreenDestination(book))
            }
        }
    }

    override fun clickRight() {
        DigitalInkManager.download(this) {
            val unit = BookUnit(name = title).apply { book = BookDb(newBookId) }
            navigator?.navigate(com.lcg.word.screen.destinations.SpellScreenDestination(unit))
        }
    }
}